from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session

from app.crud import users as crud
from app.schemas.users import UserCreate, UpdateUser, RegisterUser
from app.utils.databases import get_db
from app.utils.security import verify_token


router = APIRouter(prefix="/users")

oauth2_schema = OAuth2PasswordBearer(tokenUrl="/api/v1/token")


@router.post("/register")
def user_register(userinfo: RegisterUser, db: Session = Depends(get_db)):
    user = crud.get_user_by_username(db, userinfo.username)
    if user:
        return {"msg": f"用户名{userinfo.username}已经存在!"}
    else:
        if userinfo.password != userinfo.check_pwd:
            return {"msg": f"密码不一致: {userinfo.password} != {userinfo.check_pwd}"}
        else:
            return crud.create_user(db, userinfo)


# 创建用户
@router.post("/")
def create_user(
    user: UserCreate, db: Session = Depends(get_db), token: str = Depends(oauth2_schema)
):
    """
    添加用户
    user: 用户数据(UserCreate模型)
    db: 数据库会话
    需校验username和email是否存在
    """
    username = verify_token(token=token).get("sub", None)
    if username:
        if not crud.get_user_by_username(db, user.username):
            # 用户名不存在则创建
            if not crud.get_user_by_email(db, user.email):
                # email不存在则创建
                user_data = crud.create_user(db=db, user=user)
                response_data = {
                    "id": user_data.id,
                    "username": user_data.username,
                    "email": user_data.email,
                    "is_active": user_data.is_active,
                }
                return response_data
            else:
                # email存在则不创建
                return {"msg": f"failed: {user.email}已经存在!"}

        else:
            # 用户名已存在则不创建
            return {"msg": f"failed: {user.username}已经存在!"}
    else:
        return {"msg": "用户名不存在!"}


# 获取所有用户信息
@router.get("/")
def get_user_infos(db: Session = Depends(get_db), token: str = Depends(oauth2_schema)):
    """
    获取所以用户信息: 需要鉴权才能访问
    """
    username = verify_token(token=token).get("sub", None)
    if username:
        return crud.get_users(db)
    else:
        return {"msg": "用户名不存在"}


# 获取指定username用户信息
@router.get("/{username}")
def get_user_info(
    username: str, db: Session = Depends(get_db), token: str = Depends(oauth2_schema)
):
    """根据id查询用户信息"""
    current_user = verify_token(token=token)
    if current_user:
        userinfo = crud.get_user_by_username(db, username=username)
        if userinfo:
            return userinfo
        else:
            return {"msg": f"用户{username}不存在!"}
    else:
        return {"msg": "获取不到登录信息!"}


# 更新用户信息
@router.put("/{id}")
def update_user_info(
    id: int,
    update_data: UpdateUser,
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_schema),
):
    """更新用户信息"""
    current_user = verify_token(token=token)
    if current_user:
        return crud.update_user(db, id, update_data)
    else:
        return {"msg": "获取不到登录信息!"}


# 删除用户信息
@router.delete("/{id}")
def delete_user_info(
    id: int, db: Session = Depends(get_db), token: str = Depends(oauth2_schema)
):
    delete_user = crud.delete_user(db, id)
    if delete_user:
        return {"msg": f"用户id={id}删除成功!"}
    else:
        return {"msg": f"用户id={id}删除失败!"}
